//
//  LocationViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/2.
//  Copyright (c) 2015年 张旭. All rights reserved.
//
#import "LocationViewController.h"
#import "CusAnnotationView.h"
#import "RouteHistoryViewController.h"
#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "Tooler.h"
#import "CustomerSearchRequest.h"
#import "LocationPointAnnotation.h"
#import "BackgroundViewController.h"
#import "DropDownViewController.h"
#import "BlueAccompanyViewController.h"
#define kCalloutViewMargin          -8
#define kMapZoomLevel               19.f
#define TIMEOUT_INTERVAL            8
#define DEFAULT_POSITION_LATITUDE 39.90960456049752
#define DEFAULT_POSITION_LONGTITUDE 116.3972282409668
//#define TEST_DATA
@interface LocationViewController ()
{
    UIButton *_locationButton;
    BOOL isHaveErrMsg;
    NSString *errMsg;
}
@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property(nonatomic,retain) AppDelegate *mydelegate;
@property(nonatomic,retain) User *user;
@property(nonatomic,retain) Watch *selectWatch;
@property(nonatomic,retain) Watch *currentBLEWatch;
//@property(nonatomic,retain) Location *location;
@property(nonatomic,retain) NSArray *watchList;
@property(nonatomic) BOOL isSelectWatch;
@property (nonatomic, retain) NSString *mMainAddress;
@property (nonatomic, retain) NSString *mSubAddress;
@property (nonatomic, retain) NSString *mDateValue;
@property (nonatomic, strong) NSMutableDictionary *requestMap;

@property(nonatomic) BOOL is_open;
@property(nonatomic,strong)  UIWindow *keyWindow;
@property(nonatomic,strong)  UIWindow *alertView;
@property(nonatomic,strong)  UIWindow *alertView1;
@property(nonatomic,strong) DropDownViewController *dropView;
@property(nonatomic,strong) UIActivityIndicatorView *loadingView;
@property (strong, nonatomic) NSTimer* mTimer;

@property (nonatomic, strong) LocationPointAnnotation *currentAnnotation;
@property (nonatomic, strong) LocationPointAnnotation *keepSelectAnnotation;
@property (nonatomic,assign) int count;
@property(nonatomic) BOOL isUnderAddAnnotation;

//UI更改
@property (nonatomic,strong) MACircle *circle;
@end

@implementation LocationViewController
#ifdef TEST_DATA
int i = 1;
#endif
@synthesize mNavRightButton;
@synthesize motherTabViewController;
@synthesize currentAnnotation;
@synthesize keepSelectAnnotation;
@synthesize notiTypeLabel;
@synthesize notiTypeView;
-(void)dealloc
{
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.mydelegate=NULL;
    self.user=NULL;
    self.selectWatch=NULL;
    self.watchList=NULL;
    self.mMainAddress=NULL;
    self.mSubAddress=NULL;
    self.mDateValue=NULL;
    self.requestMap=NULL;
    self.keyWindow=NULL;
    self.alertView=NULL;
    self.alertView1=NULL;
    self.dropView=NULL;
    self.currentAnnotation=NULL;
}
- (void)viewDidLoad {
    [self clearMapView];
    [super viewDidLoad];
    self.isSyncFinish=YES;
    self.notiTypeView.layer.cornerRadius = 8;
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.isSelectWatch = NO;
    [self initDataProxy];
    [self initDropViewLayer];
    if(self.mydelegate==NULL||self.dataManager==NULL
       ||self.user==NULL||self.user.uid==NULL)
    {
        NSLog(@"%@,viewDidLoad,dataProxy is null.",location_tag);
        [LeoMsg showMsg:@"程序发生错误，code is 27"];
        return;
    }
    if(self.mydelegate.location_sync==NO)
    {
        [self syncLocationData];
        
    }
    // Do any additional setup after loading the view from its nib.
    
}

- (void)viewWillAppear:(BOOL)animated{
    self.isUnderAddAnnotation = NO;
    [super viewWillAppear:animated];
    self.count = 0;
    [self registerObservers];
    self.search = self.mydelegate.search;
    self.mapView = self.mydelegate.mapView;
    [self initControls];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.notiTypeLabel.text = @"定位中";
    [self initNavButton];
    [self initSubMapView];
    [self.view bringSubviewToFront:self.notiTypeView];
    
    //need add right nav button after view have been loaded.
    if (motherTabViewController!=NULL)
    {
        UIImage *buttonImage = [UIImage imageNamed:@"trail_icon.png"];
        UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [aButton setImage:buttonImage forState:UIControlStateNormal];
        aButton.frame = CGRectMake(0.0,0.0,25,40);
        //aButton.imageEdgeInsets = UIEdgeInsetsMake(0, -13, 0, 0);
        [aButton addTarget:self action:@selector(jumpToRoute) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:aButton];
        motherTabViewController.navigationItem.rightBarButtonItem=rightButton;
    }
    if(self.mydelegate.location_sync == YES)
    {
        if(self.isSyncFinish==YES)
        {
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue!=NULL)
            {
                dispatch_async(queue, ^{
                    self.isSyncFinish=NO;
                    [self.syncManager getWatchData:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:SYNCLASTPOSITIONDATAFINISHED object:nil  userInfo:nil];
                        self.isSyncFinish=YES;
                    }];

                });

            }

        }
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [self clearMapView];
    [self removeObservers];
    [self.mTimer invalidate];
    self.mTimer = NULL;
    [self.loadingView removeFromSuperview];
    //need disable right nav button after view disappear
    if (motherTabViewController!=NULL)
    {
        motherTabViewController.navigationItem.rightBarButtonItem=NULL;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //UITabBarItem *item = [[UITabBarItem alloc]initWithTabBarSystemItem:UITabBarSystemItemMostRecent tag:1];
        UITabBarItem *item = [[UITabBarItem alloc]initWithTitle:@"定位" image:[UIImage imageNamed:@"tb_location_icon_normal@2x"] tag:1];
        [item setSelectedImage:[UIImage imageNamed:@"tb_location_icon_hl@2x"]];
        self.tabBarItem = item;
        //self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",9];
    }
    return self;
}

-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
    self.requestMap = [[NSMutableDictionary alloc]init];
    self.mydelegate=[[UIApplication sharedApplication] delegate];
    self.user=[User sharedSingleton];
    self.watchList = [self.dataManager getWatchList:self.user.uid];
    self.selectWatch=[self.dataManager getActiveWatch:self.user.uid];
}

-(void)initDropViewLayer{
    CGRect rect = [UIScreen mainScreen].bounds;
    self.alertView=[[UIWindow alloc]initWithFrame:CGRectMake(0, 55, rect.size.width, rect.size.height)];
    self.alertView1=[[UIWindow alloc]initWithFrame:CGRectMake(0, 55, rect.size.width, rect.size.height)];
    self.dropView=[[DropDownViewController alloc] init];
}

-(void)initSubMapView{
    CGRect rect = [UIScreen mainScreen].bounds;
    self.mapView.frame = CGRectMake(0, 20+44, rect.size.width, rect.size.height-(20+44));
    //self.mapView.showsUserLocation = YES;
    self.mapView.showsCompass = NO;
    [self.mapView setRotateCameraEnabled:NO];
    [self.mapView setZoomLevel:kMapZoomLevel animated:YES];
}

-(void)initControls{
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationButton.frame = CGRectMake(CGRectGetWidth(self.mapView.bounds)-40, 10, 40, 40);
    _locationButton.autoresizingMask =
    UIViewAutoresizingFlexibleLeftMargin |
    UIViewAutoresizingFlexibleBottomMargin;
    _locationButton.backgroundColor = [UIColor clearColor];
    _locationButton.layer.cornerRadius = 5;
    
    [_locationButton addTarget:self action:@selector(locationAction) forControlEvents:UIControlEventTouchUpInside];
    [_locationButton setImage:[UIImage imageNamed:@"location_now"] forState:UIControlStateNormal];
    [self.mapView addSubview:_locationButton];
}

-(void)locationAction{
    if([Tooler checkNetworkState] == 3){
        [LeoMsg showToastMsg:@"无网络" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
        return;
    }
    self.notiTypeLabel.text = @"定位中";
    isHaveErrMsg = NO;
    [self.syncManager sendCommand:self.selectWatch.deviceUid  type:LOCATE_IMMEDIATELLY watchParams:NULL completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        
    }];
}

- (void)clearMapView
{
    self.mapView.showsUserLocation = NO;
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    //[self.mapView setMapStatus: _lastStatus animated:NO duration:0];
    self.mapView.delegate = nil;
    self.search.delegate = nil;
    [self.mapView setCompassImage:nil];
    [_locationButton removeFromSuperview];
}

- (void)initNavButton{
//     UITapGestureRecognizer *tapReconizerToOpenList = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openWatchList)];
//    [self.mNavView addGestureRecognizer:tapReconizerToOpenList];
}

- (void)jumpToRoute{
    BaseMapViewController *routeHistoryViewController = [[RouteHistoryViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    routeHistoryViewController.mapView = self.mapView;
    [self.navigationController pushViewController:routeHistoryViewController animated:YES];
    [self clearMapView];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)addAnnotationWithLocationInfo:(Location *)location
{
    //MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    LocationPointAnnotation *annotation = [[LocationPointAnnotation alloc] init];
    //if location latitude and longtitude is 0 , need set Beijing as default.
    if(location.latitude == 0 && location.longtitude == 0){
        location.latitude = DEFAULT_POSITION_LATITUDE;
        location.longtitude = DEFAULT_POSITION_LONGTITUDE;
    }
    annotation.coordinate = CLLocationCoordinate2DMake(location.latitude, location.longtitude);;
    annotation.title    = @"AutoNavi";
    annotation.subtitle = @"CustomAnnotationView";
    annotation.location = location;
    self.count = self.count + 1;//use to judge whether other annotation have been add except select watch
    if (![self.selectWatch.deviceUid isEqualToString:annotation.location.deviceUid]) {
        [self.mapView addAnnotation:annotation];
    }else if([self.selectWatch.deviceUid isEqualToString:annotation.location.deviceUid]){
        keepSelectAnnotation = annotation;
    }
    if ([self.selectWatch.deviceUid isEqualToString:keepSelectAnnotation.location.deviceUid]
         && !isHaveErrMsg
         && self.count == [self.watchList count]) {
        if (keepSelectAnnotation.location.latitude == 0
            && keepSelectAnnotation.location.longtitude == 0) {
            self.notiTypeLabel.text = @"无定位数据";
        }else if(keepSelectAnnotation.location.locateType == 0)//GPS
        {
            self.notiTypeLabel.text = [NSString stringWithFormat:@"%@定位",[self convertLocType:keepSelectAnnotation.location.locateType]];
        }else{
            self.notiTypeLabel.text = [NSString stringWithFormat:@"%@定位, %.0f米",[self convertLocType:keepSelectAnnotation.location.locateType] , keepSelectAnnotation.location.radius];
        }
        [self.mapView addAnnotation:keepSelectAnnotation];
        self.isUnderAddAnnotation = NO;
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(keepSelectAnnotation.location
                                                                     .latitude, keepSelectAnnotation.location.longtitude)animated:YES];
        [self.mapView selectAnnotation:keepSelectAnnotation animated:YES];
        [self.mapView setZoomLevel:kMapZoomLevel animated:YES];
        //[LeoMsg showToastMsg:@"数据加载成功" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
        [self.loadingView stopAnimating];
        [self.loadingView removeFromSuperview];
    }else if(isHaveErrMsg){
        //TODO
    }

}

- (CGSize)offsetToContainRect:(CGRect)innerRect inRect:(CGRect)outerRect
{
    CGFloat nudgeRight = fmaxf(0, CGRectGetMinX(outerRect) - (CGRectGetMinX(innerRect)));
    CGFloat nudgeLeft = fminf(0, CGRectGetMaxX(outerRect) - (CGRectGetMaxX(innerRect)));
    CGFloat nudgeTop = fmaxf(0, CGRectGetMinY(outerRect) - (CGRectGetMinY(innerRect)));
    CGFloat nudgeBottom = fminf(0, CGRectGetMaxY(outerRect) - (CGRectGetMaxY(innerRect)));
    return CGSizeMake(nudgeLeft ?: nudgeRight, nudgeTop ?: nudgeBottom);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    [self removeObservers];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - MAMapViewDelegate


- (void)searchReGeocodeWithLocationInfo:(Location *)location
{
    AMapReGeocodeSearchRequest *regeo = [[AMapReGeocodeSearchRequest alloc] init];
    regeo.location                    = [AMapGeoPoint locationWithLatitude:location.latitude longitude:location.longtitude];
    regeo.requireExtension            = YES;
    [self.requestMap setValue:location forKey:[NSString stringWithFormat:@"%@",regeo]];
    NSLog(@"%@,Before ReGoecodeSearch , Location = %@",location_tag,location.description);
    [self.search AMapReGoecodeSearch:regeo];
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        //[self.mapView selectAnnotation:reGeocodeAnnotation animated:YES];
        Location *location = [[Location alloc]init];
        location = [self.requestMap objectForKey:[NSString stringWithFormat:@"%@",request]];
        location.mainAddress = [NSString stringWithFormat:@"%@%@",
                                response.regeocode.addressComponent.streetNumber.street?:@"",
                                response.regeocode.addressComponent.streetNumber.number?:@""];
        location.subAddress = [NSString stringWithFormat:@"%@",
                               response.regeocode.formattedAddress?:@""];
        NSLog(@"%@,After ReGoecodeSearchDone , Location = %@",location_tag,location.description);
        [self addAnnotationWithLocationInfo:location];
        
        
        //UI更改
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(request.location.latitude, request.location.longitude);
        [self.mapView removeOverlays:self.mapView.overlays];

        self.circle = [MACircle circleWithCenterCoordinate:coordinate radius:location.radius]
        ;
        [self.mapView addOverlay:self.circle];

    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[LocationPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        
        CusAnnotationView *annotationView = (CusAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[CusAnnotationView alloc] initWithAnnotation:annotation
                                                           reuseIdentifier:customReuseIndetifier];
        }
        // must set to NO, so we can show the custom callout view.
        annotationView.canShowCallout   = NO;
        annotationView.draggable        = NO;
        annotationView.calloutOffset    = CGPointMake(0, 0);
        annotationView.centerOffset     = CGPointMake(0, -35);
        LocationPointAnnotation *locationPointAnnotation = annotation;
        self.isSelectWatch = NO;
        if ([self.selectWatch.deviceUid isEqualToString:locationPointAnnotation.location.deviceUid]) {
            self.isSelectWatch = YES;
        }
        if (self.isSelectWatch == YES) {
            annotationView.portrait         = [UIImage imageNamed:@"location1@2x"];
            self.currentAnnotation = annotation;
            //[annotationView setUserInteractionEnabled:YES];
        }
        else{
            annotationView.portrait         = [UIImage imageNamed:@"location2@2x"];
            //[annotationView setUserInteractionEnabled:NO];
        }
        Watch *watch = [self.dataManager getWatch:locationPointAnnotation.location.deviceUid];
        if (watch.pic_url != NULL&&![watch.pic_url isEqualToString:@"(null)"]) {
            [annotationView setAvatarWithURL:[[Tooler getDocumentDirectory] stringByAppendingString:watch.pic_url]];
        }
        else
        {
            if(watch.gender == 1){
              [annotationView setAvatarWithURL:@"avater_girl.png"];
            }else{
              [annotationView setAvatarWithURL:@"avater_boy.png"];
            }
        }
        annotationView.deviceUid=watch.deviceUid;
        annotationView.mainLabelValue     = locationPointAnnotation.location.mainAddress;
        annotationView.subLabelValue      = locationPointAnnotation.location.subAddress;
        NSString *gen_time = [self second2Stringformat:locationPointAnnotation.location.gen_time withFormatter:@"HH:mm"];
        //NSDate *current = [NSDate date];
//      NSDateFormatter *formate = [[NSDateFormatter alloc]init];
//      [formate setDateFormat:@"HH:mm"];
        //NSString *currentTime = [formate stringFromDate:current];
        annotationView.dateLabelValue     = [NSString stringWithFormat:@"上次定位 %@",gen_time];
        annotationView.phoneNumber        = watch.sim;
        annotationView.batteryLabelValue  = watch.battery;
        return annotationView;
    }
    return nil;
}


#pragma mark - Action Handle

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    /* Adjust the map center in order to show the callout view completely. */
    if ([view isKindOfClass:[CusAnnotationView class]]) {
        CusAnnotationView *cusView = (CusAnnotationView *)view;
        CGRect frame = [cusView convertRect:cusView.calloutView.frame toView:self.mapView];

        frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin));

        if (!CGRectContainsRect(self.mapView.frame, frame))
        {
            /* Calculate the offset to make the callout view show up. */
            CGSize offset = [self offsetToContainRect:frame inRect:self.mapView.frame];

            CGPoint screenAnchor = [self.mapView getMapStatus].screenAnchor;
            CGPoint theCenter = CGPointMake(self.mapView.bounds.size.width * screenAnchor.x, self.mapView.bounds.size.height * screenAnchor.y);
            theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height);

            CLLocationCoordinate2D coordinate = [self.mapView convertPoint:theCenter toCoordinateFromView:self.mapView];

            [self.mapView setCenterCoordinate:coordinate animated:YES];
        }
        
    }
}

//UI更改
-(MAOverlayView *)mapView:(MAMapView *)mapView viewForOverlay:(id<MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MACircle class]])
    {
        MACircleView *circleView = [[MACircleView alloc] initWithCircle:overlay];
        
        circleView.lineWidth    = 2.f;
        circleView.strokeColor  = [UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0];
        circleView.fillColor    = [UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:0.2];
        circleView.lineDash     = NO;
        
        return circleView;
    }
    return nil;
}


//Data Related Functions
-(void)syncLocationData
{
    isHaveErrMsg = NO;
    errMsg = NULL;
    NSLog(@"%@,syncLocationData entered",location_tag);
    @try {
        dispatch_group_t serviceGroup = dispatch_group_create();
        dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        if(queue==NULL)
        {
            NSLog(@"%@,syncLocationData,queue is null",location_tag);
            return;
        }
        //dispatch_async(queue, ^{
            //dispatch_async(dispatch_get_main_queue(), ^{
                for (int i = 0; i < [self.watchList count]; i++) {
                    dispatch_group_enter(serviceGroup);
                    Watch *watch = [self.watchList objectAtIndex:i];
                    [self.syncManager getLatestPosition:watch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        dispatch_group_leave(serviceGroup);
                        if(result==SUCESS)
                        {
                            NSLog(@"%@,getLastPosition success.",location_tag);
                        }
                        else
                        {
                            isHaveErrMsg = YES;
                            if ([@"" isEqualToString:description]||description == NULL) {
                                description = @"定位失败";
                            }
                            errMsg = description;
                        }
                    }];
                }
                dispatch_group_notify(serviceGroup,dispatch_get_main_queue(),^{
                    if(isHaveErrMsg&&![errMsg isEqualToString:API_REFRESHTOKEN_INVALID_INFO]){
                        [LeoMsg showToastMsg:errMsg parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
                    }
                    [self.syncManager getWatchData:self.selectWatch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:SYNCLASTPOSITIONDATAFINISHED object:nil  userInfo:nil];
                        self.mydelegate.location_sync=YES;
                    }];
                });
    }
    @catch (NSException *exception) {
        NSLog(@"%@,syncFromServer,exception is %@",location_tag,[exception reason]);
    }
    
    
}

-(void)loadData
{
    if (self.isUnderAddAnnotation) {
        NSLog(@"loadData , now is under addAnnotation process , so skip");
        return;
    }
    self.count = 0;
    [self.mapView removeAnnotations:self.mapView.annotations];
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        [LeoMsg showMsg:@"程序发生错误，code is 28"];
        return;
    }
    if (self.loadingView == NULL) {
        self.loadingView=[LeoMsg showLoadingView];
        [self.view addSubview:self.loadingView];
    }
    [self.loadingView startAnimating];
    if (self.mTimer == NULL) {
        self.mTimer = [NSTimer scheduledTimerWithTimeInterval:TIMEOUT_INTERVAL target:self selector:@selector(timeoutHandler) userInfo:nil repeats:NO];
    }
    self.watchList = [self.dataManager getWatchList:self.user.uid];
    if (self.watchList > 0) {
        self.isUnderAddAnnotation = YES;
    }
    //获取数据库所有手表最新位置并显示
    NSLog(@"%@,loadData watch count = %lu",location_tag,(unsigned long)[self.watchList count]);
    for (int i = 0; i < [self.watchList count]; i++) {
        self.isSelectWatch = NO;
        Watch *watch = [self.watchList objectAtIndex:i];
        Location *location = [[Location alloc] init];
        location = [self.dataManager getLatestLocation:watch.deviceUid];
        //Dont need use ReGeocode need improve
        [self searchReGeocodeWithLocationInfo:location];
        //[self addAnnotationWithLocationInfo:location];
    }
    //取得当前选中的手表
    self.selectWatch=[self.dataManager getActiveWatch:user.uid];
    Location *selectLocation = [self.dataManager getLatestLocation:self.selectWatch.deviceUid];
    //[self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(selectLocation
    //                                                             .latitude, selectLocation.longtitude)animated:YES];
}

-(void)registerObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:SYNCLASTPOSITIONDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:CALLBLUEACCOMPANYVIEW object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:CHANGEWATCH object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:SELECTWATCH object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:ENTERFOREGROUND object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:LOCATIONRESULTARRIVED object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:UNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:NOTIFYBLEDEVICEDISCONNECTED object:nil];
}

-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SYNCLASTPOSITIONDATAFINISHED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CALLBLUEACCOMPANYVIEW object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CHANGEWATCH object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SELECTWATCH object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ENTERFOREGROUND object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:LOCATIONRESULTARRIVED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFYBLEDEVICEDISCONNECTED object:nil];
}

- (void)receiveNotification:(NSNotification *)sender {
    NSNotification *notifyType = (NSNotification *)sender;
    if ([notifyType.name isEqualToString:CALLBLUEACCOMPANYVIEW]) {
        if(self.mydelegate.isBLEUnderConnect){
            BlueAccompanyViewController *blueAccompanyViewController =
            [[BlueAccompanyViewController alloc]init];
            if(self.currentBLEWatch.pic_url!=NULL
               && ![self.currentBLEWatch.pic_url isEqualToString:@"(null)"]
               && ![self.currentBLEWatch.pic_url isEqualToString:@""]){
                blueAccompanyViewController.avatarImage = [UIImage imageNamed:self.currentBLEWatch.pic_url];
            }else{
                if (self.currentBLEWatch.gender == 1) {
                    blueAccompanyViewController.avatarImage = [UIImage imageNamed:@"avater_girl.png"];
                }else{
                    blueAccompanyViewController.avatarImage = [UIImage imageNamed:@"avater_boy.png"];
                }
            }
            blueAccompanyViewController.statusLabelValue = self.currentBLEWatch.nickname;
            blueAccompanyViewController.macAddress = self.currentBLEWatch.mac;
            blueAccompanyViewController.userID = self.user.uid;
            blueAccompanyViewController.isStartByDisConnectNoti = NO;
            [self presentViewController:blueAccompanyViewController animated:YES completion:nil];
        }else{
            BlueAccompanyViewController *blueAccompanyViewController =
            [[BlueAccompanyViewController alloc]init];
            if(self.selectWatch.pic_url!=NULL
               && ![self.selectWatch.pic_url isEqualToString:@"(null)"]
               && ![self.selectWatch.pic_url isEqualToString:@""]){
                blueAccompanyViewController.avatarImage = [UIImage imageNamed:self.selectWatch.pic_url];
            }else{
                if (self.selectWatch.gender == 1) {
                    blueAccompanyViewController.avatarImage = [UIImage imageNamed:@"avater_girl.png"];
                }else{
                    blueAccompanyViewController.avatarImage = [UIImage imageNamed:@"avater_boy.png"];
                }
            }
            blueAccompanyViewController.statusLabelValue = self.selectWatch.nickname;
            blueAccompanyViewController.macAddress = self.selectWatch.mac;
            blueAccompanyViewController.userID = self.user.uid;
            blueAccompanyViewController.isStartByDisConnectNoti = NO;
            self.currentBLEWatch = self.selectWatch;
            [self presentViewController:blueAccompanyViewController animated:YES completion:nil];
        }
        return;
    }else if([notifyType.name isEqualToString:NOTIFYBLEDEVICEDISCONNECTED]){
        BlueAccompanyViewController *blueAccompanyViewController =
        [[BlueAccompanyViewController alloc]init];
        if(self.selectWatch.pic_url!=NULL
           && ![self.selectWatch.pic_url isEqualToString:@"(null)"]
           && ![self.selectWatch.pic_url isEqualToString:@""]){
            blueAccompanyViewController.avatarImage = [UIImage imageNamed:self.selectWatch.pic_url];
        }else{
            if (self.selectWatch.gender == 1) {
                blueAccompanyViewController.avatarImage = [UIImage imageNamed:@"avater_girl.png"];
            }else{
                blueAccompanyViewController.avatarImage = [UIImage imageNamed:@"avater_boy.png"];
            }
        }
        blueAccompanyViewController.statusLabelValue = self.selectWatch.nickname;
        blueAccompanyViewController.macAddress = self.selectWatch.mac;
        blueAccompanyViewController.userID = self.user.uid;
        blueAccompanyViewController.isStartByDisConnectNoti = YES;
        [self presentViewController:blueAccompanyViewController animated:YES completion:nil];
        return;
    }else if([notifyType.name isEqualToString:CHANGEWATCH]){
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mapView removeAnnotations:self.mapView.annotations];
            [self loadData];
        });
        return;
    }else if([notifyType.name isEqualToString:SELECTWATCH]){
        NSLog(@"receive select msg");
    }else if([notifyType.name isEqualToString:ENTERFOREGROUND]){
        [self syncLocationData];
        NSLog(@"receive EnterForeGround msg");
        return;
    }else if ([notifyType.name isEqualToString:LOCATIONRESULTARRIVED]){
        if (!self.isUnderAddAnnotation) {
            self.isUnderAddAnnotation = YES;
            [self.mapView removeAnnotation:self.currentAnnotation];
            User *user=[User sharedSingleton];
            self.selectWatch=[self.dataManager getActiveWatch:user.uid];
            self.watchList = [self.dataManager getWatchList:self.user.uid];
            Location *location = [[Location alloc] init];
            location = [self.dataManager getLatestLocation:self.selectWatch.deviceUid];
            self.count = [self.watchList count]-1;
            [self searchReGeocodeWithLocationInfo:location];
            [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(location.latitude, location.longtitude)animated:YES];
        }else{
            NSLog(@"receive location Result Arrived , but now is under process add logic , so skip");
        }
        return;
    }else if ([notifyType.name isEqualToString:UNBINDDEVICE]){
        NSLog(@"receive unbind msg");
    }
    [self loadData];
    
}

//temp use
-(NSString *)second2Stringformat:(NSString *)second withFormatter:(NSString *)formatter
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:[second doubleValue]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:formatter];
    
    return [dateFormatter stringFromDate:date];
}

-(void)openWatchList
{
    if(!self.is_open)
    {
        self.keyWindow = [[[UIApplication sharedApplication] delegate] window];
        BackgroundViewController *backView=[[BackgroundViewController alloc] init];
        self.alertView1.rootViewController=backView;
        [self.keyWindow addSubview:self.alertView1];
        [self.alertView1 setWindowLevel:UIWindowLevelAlert];
        [self.alertView1 makeKeyAndVisible];

        [self.dropView setMotherWindow:self.alertView];
        self.alertView.rootViewController=self.dropView;
        [self.keyWindow addSubview:self.alertView];
        [self.alertView setWindowLevel:UIWindowLevelAlert];
        [self.alertView makeKeyAndVisible];
        self.is_open=YES;
        //self.watchBtn.imageView.image=[UIImage imageNamed:@"list_icon_close@2x.png"];
    }
    else
    {
        self.alertView.hidden=YES;
        self.alertView1.hidden=YES;
        self.is_open=NO;
        //self.watchBtn.imageView.image=[UIImage imageNamed:@"list_icon_open@2x.png"];
    }
}

-(NSString *)convertLocType:(int)type{
    switch (type) {
        case 0:
            return @"GPS";
            break;
            
        case 1:
            return @"网络";
            break;
            
        case 2:
            return @"网络";
            break;

        default:
            return @"";
            break;
    }
}

-(void)timeoutHandler{
    for (UIView *v in  self.view.subviews){
        if ([v isKindOfClass:[UIActivityIndicatorView class]]) {
            [v removeFromSuperview];
            self.isUnderAddAnnotation = NO;
            //[LeoMsg showToastMsg:@"定位失败" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
        }
    }
}

@end
